package com.wude.tools;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mc.developmentkit.utils.MCUtils;
import com.mc.developmentkit.utils.ToastUtil;
import com.wude.bean.AppInfo;
import com.wude.bean.SettingInfo;
import com.wude.bean.UserInfo;
import com.wude.guild.app.GuildApplication;
import com.wude.guild.manager.DownLoadServers;
import com.wude.http.HttpCom;

import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.common.Callback.Cancelable;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executor;

public class Utils {

//    static {
//        System.loadLibrary("encryption");
//    }

    private static long b = 0;
    private static long c;
    private static long d;
    private static long l;
    private static PopupWindow popupWindow;
    private static TextView size;
    private static TextView title;
    private static TextView spend;
    private static ProgressBar progressBar;
    private static View pro;
    private final static Executor exec = new PriorityExecutor(3, true);//成员常量
    private static TextView message;
    private static Button dialog_button_cancel;
    private static Button dialog_button_ok;

    public static Context getContext() {

        return GuildApplication.getApplication();
    }

    public static void TS(String content) {
        Toast.makeText(getContext(), content, Toast.LENGTH_SHORT).show();
    }

    public static String getCurrentTime(String format) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
        String currentTime = sdf.format(date);
        return currentTime;
    }

    public static String getCurrentTime() {
        return getCurrentTime("yyyy-MM-dd  HH:mm:ss");
    }

    public static void Fill(View view, String url) {
        MCUtils.fillImage((ImageView) view, url);
    }

    public static int dipToPx(Context paramContext, float paramFloat) {
        return (int) (0.5f + (paramContext.getResources().getDisplayMetrics().density * paramFloat));
    }

    public static int pxToDip(Context paramContext, float paramFloat) {
        return (int) (0.5f + (paramFloat / paramContext.getResources().getDisplayMetrics().density));
    }

    /**
     * dip 转 px
     *
     * @param dip
     * @return
     */
    public static int dip2px(int dip) {
        //
        // 公式： dp = px / (dpi / 160) px = dp * (dpi / 160)
        // dp = px / denisity
        // px = dp * denisity;
        DisplayMetrics metrics = x.app().getResources().getDisplayMetrics();
        float density = metrics.density;
        return (int) (dip * density + 0.5f);
    }


    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9

------------------------------------------------
13(老)号段：130、131、132、133、134、135、136、137、138、139
14(新)号段：145、147
15(新)号段：150、151、152、153、154、155、156、157、158、159
17(新)号段：170、171、173、175、176、177、178
18(3G)号段：180、181、182、183、184、185、186、187、188、189
    */
        String telRegex = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、4、5、7、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);

    }

    public static String getBase64String(byte[] bytes, int flag) {
        return Base64.encodeToString(bytes, flag);
    }


    /**
     * 判断包是否安装
     *
     * @param context
     * @return
     */

    public static boolean isInstall(Context context, String path) {

        try {
            if (path == null || path.equals("")) {
                Log.e("包名为空", "包名为空");
                return false;
            }
            PackageManager packageManager = context.getPackageManager();
            packageManager.getPackageInfo(path, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    /**
     * 安装应用程序
     *
     * @param context
     * @param apkFile
     */
    public static void installApp(Context context, File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(context, "com.wude.guild.fileProvider", apkFile);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    /**
     * 打开应用程序
     *
     * @param context
     */
    public static void openApp(Context context, String path) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(path);
        context.startActivity(intent);
    }

    public static double getM(long a) {
        l = a / (1024 * 1024);
        BigDecimal b = new BigDecimal(l);
        double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1;
    }

    public static String getSpent(long a) {
        c = a - b;
        d = c / 1024;
        b = a;
        if (d > 1024) {
            return d / 1024 + "M/s";
        }
        return d + "kb/s";
    }


    public static String getRequestParamString(Map<String, String> paramMap) {
        if (null == paramMap || paramMap.size() < 1) {
            return "";
        }
        List<Map.Entry<String, String>> mappingList = new ArrayList<Map.Entry<String, String>>(
                paramMap.entrySet());
        Collections.sort(mappingList,
                new Comparator<Map.Entry<String, String>>() {

                    @Override
                    public int compare(Map.Entry<String, String> mapping1,
                                       Map.Entry<String, String> mapping2) {
                        return mapping1.getKey().compareTo(mapping2.getKey());
                    }
                });
        JSONObject jsonparam = new JSONObject();
        String values = "";
        try {
            for (Map.Entry<String, String> mapping : mappingList) {
                String key = mapping.getKey().trim();
                String value = mapping.getValue();
                // MCLog.e(TAG, key + ":" + value);
                jsonparam.put(key, value);

                values += mapping.getValue();
            }
            String key = getMd5(values.trim() + "mengchuang");
            jsonparam.put("md5_sign", key);
            return jsonparam.toString();
        } catch (Exception e) {
            System.out.println("加密出错了" + e.toString());
        }
        return "";
    }

    //public native static String getEncryption(String s);


    //静态方法，便于作为工具类
    public static String getMd5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getChange(int shu) {
        if (shu < 10000) {

            return shu + "次+";
        }
        if (shu >= 10000 && shu <= 99999999) {
            Double jieguo = (double) (shu % 10000);
            String a = new DecimalFormat("#").format(jieguo);
            return a + "万次+";
        }
        if (shu > 100000000) {
            long c = shu / 100000000;
            String b = new DecimalFormat("#").format(c);
            return b + "亿次+";
        }
        return null;
    }

    public static void instell(AppInfo a, Activity b) {
        SettingInfo findById;
        try {
            DbManager db = DbUtils.getDB();
            findById = db.findById(SettingInfo.class, 1);
            if (findById != null && findById.tan == 2) {
                if (a.anzhuang != 2) {
                    a.anzhuang = 2;
                    Log.e("执行了ssss", "执行了ssss");
                    db.saveOrUpdate(a);
                    InStall(a, b);
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public static void InStall(AppInfo app, Activity a) {
        DownLoadServers.getDownloadManager(a).install(app);
    }

    public static void an1(AppInfo app, Activity a) {
        DownLoadServers.getDownloadManager(a).isInstall(app);
    }

    public static int verison_update(String ver, String url) {
        try {
            GuildApplication app = (GuildApplication) GuildApplication
                    .getApplication();

            int localverison = app.getPackageManager().getPackageInfo(
                    app.getPackageName(), 0).versionCode;
            Log.e("本地版本号：", localverison + "");
            if (ver.equals("null")) {
                ver = "" + localverison;
            }
            float serververison = Float.parseFloat(ver);// null不能转化为flat
            if (serververison > localverison) {
                Log.e("版本更新", "发现新版本需要更新");
                return 1;    //需要更新
            } else if (serververison == localverison) {
                Log.e("版本更新", "版本相同无需更新");
                return 2;
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            Log.e("版本号格式异常", e.toString());
            return 3;
        }
        Log.e("版本更新", "服务器版本小于本地版本，后台填写错误");
        return 4;
    }

    private static void Prompt() {

    }

    //下载
    protected static void StartDown(String url) {
        RequestParams entity = new RequestParams(url);
        entity.setAutoResume(true);//是否断点下载
        entity.setAutoRename(false);//下载完成后是否自动重命名
        entity.setCancelFast(true);//快速取消
        entity.setExecutor(exec);//线程池
        entity.setSaveFilePath(getApkFile(String.valueOf(00001)).getAbsolutePath());//文件保存路径
        Cancelable cancelable = x.http().get(entity, new Callback.ProgressCallback<File>() {

            @Override
            public void onCancelled(CancelledException arg0) {
            }

            @Override
            public void onError(Throwable arg0, boolean arg1) {
                System.out.println("xiazaishibai+++" + arg0);
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onSuccess(File arg0) {
                File apkFile = getApkFile(String.valueOf(01));
                Utils.installApp(Utils.getContext(), apkFile);
            }

            @Override
            public void onLoading(long arg0, long arg1, boolean arg2) {
                int progress = (int) (arg1 * 100f / arg0 + 0.5f);
                DecimalFormat df2 = new DecimalFormat("##.0");
                String format = df2.format(arg0 / 1024 / 1024);
                String format1 = df2.format(arg1 / 1024 / 1024);
                size.setText(format + "M" + "/" + format1 + "M");
                spend.setText(Utils.getSpent(arg1));
                progressBar.setProgress(progress);
            }

            @Override
            public void onStarted() {
                size.setText("0M/0M");
                spend.setText("0kb/m");
                progressBar.setProgress(0);
            }

            @Override
            public void onWaiting() {

            }
        });
    }

    public static File getApkFile(String packageName) {
        String dir = FileUtils.getDownloadDir().getAbsolutePath();
        return new File(dir, packageName + ".apk");
    }

    public static File getImageFile(String imgId) {
        String dir = FileUtils.getIconDir().getAbsolutePath();
        return new File(dir, imgId + ".png");
    }

    /**
     * 根据路径获得应用包名
     *
     * @param context
     * @param path
     * @return
     */
    public static String GetPackageName(Context context, String path) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo pm = packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
        if (pm != null) {
            ApplicationInfo Info = pm.applicationInfo;
            return Info.packageName;
        } else {
            return "";
        }
    }

    /**
     * 使状态栏透明 * <p> * 适用于图片作为背景的界面,此时需要图片填充到状态栏 * * @param activity 需要设置的activity
     */
    public static boolean setTranslucent(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            //activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            return true;
        } else {
            return false;
        }
    }

    public static void initActionBarPosition(FragmentActivity activity, ImageView view) {
        boolean setTranslucent = Utils.setTranslucent(activity);
        if (setTranslucent == true) {
            int height = Utils.getStatusHeight(activity);
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            layoutParams.height = height;
            view.setLayoutParams(layoutParams);
        } else {
            return;
        }
    }


    /**
     * @param activity
     * @return > 0 success; <= 0 fail
     */
    public static int getStatusHeight(Activity activity) {
        int statusHeight = 0;
        Rect localRect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
                statusHeight = activity.getResources().getDimensionPixelSize(i5);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }


    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        listView.setLayoutParams(params);
    }


    public static void setGridViewHeight(GridView gridview) {
        // 获取gridview的adapter
        ListAdapter listAdapter = gridview.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int numColumns = 2;//gridview.getNumColumns(); //5
        int totalHeight = 0;
        // 计算每一列的高度之和
        for (int i = 0; i < listAdapter.getCount(); i += numColumns) {
            // 获取gridview的每一个item
            View listItem = listAdapter.getView(i, null, gridview);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }
        int count = listAdapter.getCount();
        int i = (int) ((int) (count / 2) + 0.5);
        int verticalSpacing = gridview.getVerticalSpacing();
        // 获取gridview的布局参数
        ViewGroup.LayoutParams params = gridview.getLayoutParams();
        params.height = totalHeight + (verticalSpacing * i);
        gridview.setLayoutParams(params);
    }

    public static UserInfo getUser() {
        DbManager db = DbUtils.getDB();
        try {
            UserInfo findFirst = db.selector(UserInfo.class).where("dl", "=", 2).findFirst();
            return findFirst;
        } catch (DbException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getSize(long yixia, long size) {
        String yixiazai = CleanMessageUtil.getFormatSize(yixia);
        String zsize = CleanMessageUtil.getFormatSize(size);
        return yixiazai + "/" + zsize;
    }

    /**
     * 获取设置Bean
     *
     * @return
     */
    public static SettingInfo getSettingBean() {
        try {
            DbManager db = DbUtils.getDB();
            SettingInfo byId = db.findById(SettingInfo.class, 1);
            if (byId == null) {
                SettingInfo settingInfo = new SettingInfo();
                settingInfo.id = 1;
                settingInfo.delete = 2;
                settingInfo.tan = 2;
                settingInfo.wlti = 2;
                db.saveOrUpdate(settingInfo);
                return settingInfo;
            }
            return byId;
        } catch (DbException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取正在登录的User
     *
     * @return
     */
    public static UserInfo getLoginUser() {
        DbManager db = DbUtils.getDB();
        try {
            UserInfo byId = db.findById(UserInfo.class, 1);
            if (byId != null) {
                return byId;
            } else {
                return null;
            }
        } catch (DbException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static boolean copy(String text) {
        if (!TextUtils.isEmpty(text)) {
            ClipboardManager cmb = (ClipboardManager) x.app().getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(text);
            ToastUtil.showToast("已成功复制到粘贴板");
            return true;
        } else {
            ToastUtil.showToast("复制失败");
            return false;
        }
    }


    /**
     * /** 获取IMEI
     */
    @SuppressLint("MissingPermission")
    public static String getIMEI(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imei = telephonyManager.getDeviceId();
        Log.e("Utils里获取的IMEI", imei);
        return imei;
    }

    /**
     * 获取下载链接
     *
     * @param handler
     * @param id
     */
    public static void getDownLoadUrl(Handler handler, int id) {
        Log.e("游戏ID", "" + id);
        HashMap<String, String> map = new HashMap<>();
        map.put("game_id", "" + id);
        HttpCom.POST(handler, HttpCom.getDownURL(), map, false);
    }


    public static boolean getFu(String s) {
        long l = Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10));
        Log.e("当前手机时间戳", "" + l);
        Log.e("服务器时间戳", s);
        Long aLong = Long.valueOf(s);
        if (aLong > l) {
            Log.e("未开服", "未开服");
            return false;
        } else {
            Log.e("已开服", "已开服");
            return true;
        }
    }


    /**
     * 截取安卓版
     *
     * @param s
     * @return
     */
    public static String getJieQu(String s) {
        int i = s.indexOf("安卓版");
        if (i != -1) {
            String substring = s.substring(0, i - 1);
            return substring;
        } else {
            return s;
        }
    }


    /**
     * 每3个数字用“，”隔开(千位数分隔符)
     *
     * @param str
     * @return
     */
    public static String addComma(String str) {
        if (str.toString().length() > 3) {
            String reverseStr = new StringBuilder(str).reverse().toString();
            String strTemp = "";
            for (int i = 0; i < reverseStr.length(); i++) {
                if (i * 3 + 3 > reverseStr.length()) {
                    strTemp += reverseStr.substring(i * 3, reverseStr.length());
                    break;
                }
                strTemp += reverseStr.substring(i * 3, i * 3 + 3) + ",";
            }
            if (strTemp.endsWith(",")) {
                strTemp = strTemp.substring(0, strTemp.length() - 1);
            }
            String resultStr = new StringBuilder(strTemp).reverse().toString();
            return resultStr;
        } else {
            return str;
        }
    }

    /**
     * MB转换成GB，保留一位小数
     *
     * @return
     */
    public static String getGB(int size) {
        float num = (float) size / 1024;
        DecimalFormat df = new DecimalFormat("0.0");//格式化小数
        return df.format(num); //返回的是String类型
    }

}
